import config from '@/config/config.js';

//校验邮箱格式
export function checkEmail(email) {
	return RegExp(/^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/).test(
		email);
}

//校验手机格式
export function checkMobile(mobile) {
	return RegExp(/^1[34578]\d{9}$/).test(mobile);
}

/* 格式化时间
 * @method fmtDate
 * @param {String} str 时间戳字符串
 * @param {String} d 日期格式，默认为时间格式,1年月日,2月日时分,3年月1号
 * @return {String} 返回格式化之后的日期
 */
export const fmtDate = (str, d) => {
	let dt = str ? new Date(str) : new Date();
	let year = dt.getFullYear();
	let month = fixed2(dt.getMonth() + 1);
	let date = fixed2(dt.getDate());
	let hours = fixed2(dt.getHours());
	let minutes = fixed2(dt.getMinutes());
	let secounds = fixed2(dt.getSeconds());
	let times = '';
	if (d == 1) {
		times = `${year}-${month}-${date}`;
	} else if (d == 2) {
		times = `${month}-${date} ${hours}:${minutes}`;
	} else if (d == 3) {
		times = `${year}-${month}-01`;
	} else {
		times = `${year}-${month}-${date} ${hours}:${minutes}:${secounds}`;
	}
	return times;
}

/* 保留两位小数
 * @method fixed2
 * @param {String} str 需要转换的字符串
 * @return {String} 返回两位小数
 */
export const fixed2 = (str) => {
	return Number.parseInt(str) < 10 ? '0' + str : str;
}


/* 手机号隐藏4位
 * @method MobileHide
 * @param {String} value 手机号
 * @return {String} 隐藏中间四位手机号
 */
export const mobileHide = value => {
	return value.replace(/^(\d{3})\d{4}(\d{4})$/, "$1****$2");
}

/* 根据出生日期计算年龄
 * @method getAge
 * @param {String} birthday 出生年月
 * @return {String} 年龄
 */
export const getAge = function(birthday) {
	//出生时间 毫秒
	var birthDayTime = new Date(birthday).getTime();
	//当前时间 毫秒
	var nowTime = new Date().getTime();
	//一年毫秒数(365 * 86400000 = 31536000000)
	return Math.ceil((nowTime - birthDayTime) / 31536000000);
}

/* 腾讯地图经纬度转化为百度地图经纬度
 * @method lng 经度
 * @method lat 维度
 * @param {String} birthday 出生年月
 * @return {String} 年龄
 */
export const qqMapTransBMap = function(lng, lat) {
	let x_pi = 3.14159265358979324 * 3000.0 / 180.0;
	let x = lng;
	let y = lat;
	let z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi);
	let theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi);
	let lngs = z * Math.cos(theta) + 0.0065;
	let lats = z * Math.sin(theta) + 0.006;
	return {
		lng: lngs,
		lat: lats
	}
}


/* 获取定位信息
 * @method that this指向
 */
export const getLocation = function(that, fun = e => {}) {
	uni.getLocation({
		type: 'gcj02',
		geocode: true,
		success(res) {
			console.log(res, 'success')
			getLocationInfo(res.longitude, res.latitude, that, fun)
		},
		fail(err) {
			console.log(err)
			if ((err.errCode && err.errCode === 2) || (err.errNo && err.errNo === 21301 && err.errMsg
					.indexOf('locate fail') >= 0)) {
				uni.showModal({
					title: '提示',
					content: '请打开手机GPS定位',
					showCancel: false
				});
			} else if (err.errMsg.indexOf('auth den') >= 0) {
				that.show = true;
			} else if (err.errMsg.indexOf('onLocationChange') >= 0) {
				console.log('onLocationChange');
			}
		}
	});
}


/* 获取定位地址详情
 * @method lng 经度
 * @method lat 维度
 * @method fun 运行函数
 */
export const getLocationInfo = function(lng, lat, that, fun = e => {}) {
	let data = qqMapTransBMap(lng, lat);
	uni.showLoading({
		title: '加载中'
	});
	uni.request({
		url: 'https://api.map.baidu.com/reverse_geocoding/v3/',
		data: {
			ak: 'ppPFOy4mPTGV7i5WexVhCn5yj3MGPdGZ',
			location: `${data.lat},${data.lng}`,
			output: 'json',
			pois: 1
		},
		success: (res) => {
			uni.hideLoading()
			console.log(res)
			if (that.localization) {
				that.$u.vuex('localization', Object.assign(that.localization, {
					city_code: res.data.result.addressComponent.adcode.substr(0, 4) + '00',
					city: res.data.result.addressComponent.city
				}));
			} else {
				that.$u.vuex('localization', Object.assign({
						city_code: res.data.result.addressComponent.adcode.substr(0, 4) + '00'
					}, res.data.result
					.addressComponent, res.data.result.location));
			}
			console.log(that.localization, '定位信息')
			fun();
		},
		fail() {
			uni.hideLoading()
		}
	})
}
/* 通过中文地区获取详细信息（经纬度等）
 * @method e 地区
 * @method that this指向
 * @method fun 运行函数
 */
export const getAreaDetails = function(e, that, fun = e => {}) {
	uni.request({
		url: 'https://api.map.baidu.com/geocoding/v3/',
		data: {
			ak: 'ppPFOy4mPTGV7i5WexVhCn5yj3MGPdGZ',
			address: e,
			output: 'json'
		},
		success: (res) => {
			let data = res.data;
			if (data.status === 0) {
				getLocationInfo(data.result.location.lng, data.result.location.lat, that, fun);
			} else {
				that.$u.toast('该城市在百度地图内不存在');
			}
		}
	})
}
/* 手机验证码获取
 * @method that this指向
 * @method phone 手机号
 * @method fun 运行函数
 */
export const getVerification = function(that, phone, fun = e => {}) {
	if (that.$refs.uCode.canGetCode) {
		that.$u.api.sms({
			phone: phone
		}).then(res1 => {
			let data = res1.result;
			if (res1.code === 200) {
				// that.$u.toast('验证码已发送');
				that.$refs.uCode.start();
				fun();
			} else {
				that.$u.toast(res1.message);
			}
		});
	} else {
		that.$u.toast('网络异常');
	}
}

/* websocet 连接
 * @method m 值
 */
export const websocetStorage = function(that, sysAllDictItems) {
	// 存储数据字典
	that.$u.vuex('sysAllDictItems', sysAllDictItems);
	// websocket连接
	// that.$store.commit('WEBSOCKET_INIT');
}

/* 获取数据字典对应描述
 * @method m 值
 */
export const getDistText = function(key, value) {
	if (!key) return;
	let data = uni.getStorageSync('lifeData') ? uni.getStorageSync('lifeData').sysAllDictItems : [];
	if (key && value) {
		if (data[key]) {
			let filterValue = data[key].filter(item => item.value === value);
			if (filterValue.length > 0) {
				return filterValue[0].text;
			}
		}
	} else if (key) {
		let arr = key.split(',');
		let obj = {};
		arr.map(e => {
			obj[e] = data[e]
		})
		return obj[key];
	}
}

/* 拨打电话
 * @method phoneNumber 手机号
 */
export const onCell = function(phoneNumber) {
	uni.makePhoneCall({
		phoneNumber: phoneNumber
	});
}

/* 获取当前界面路径
 * @method fun 回调事件
 */
export const getCurrentPageUrl = function() {
	const pages = getCurrentPages()
	const currentPage = pages[pages.length - 1]
	const url = `/${currentPage.route}`
	return url
}

/**
 * 数字转整数 如 100000 转为10万
 * @param {需要转化的数} value
 * @param {需要保留的小数位数} point
 */
export const tranNumber = (value, point) => {
	if (value) {
		let numStr = value.toString()
		// 十万以内直接返回
		if (numStr.length < 6) {
			return numStr;
		} else if (numStr.length > 8) { //大于8位数是亿
			let decimal = numStr.substring(numStr.length - 8, numStr.length - 8 + point);
			return parseFloat(parseInt(numStr / 100000000) + '.' + decimal) + '亿';
		} else if (numStr.length > 5) { //大于6位数是十万 (以10W分割 10W以下全部显示)
			let decimal = numStr.substring(numStr.length - 4, numStr.length - 4 + point)
			return parseFloat(parseInt(numStr / 10000) + '.' + decimal) + 'w';
		}
	} else {
		return value
	}
}

/**
 * 检查登录状态是否过期
 * @param {this指向} that
 * @param {执行方法} fun
 */
export const checkLogin = (that, fun) => {
	if (that.appletsInfo.loginCode) {
		uni.checkSession({
			success(res) {
				console.log(res);
				fun();
			},
			fail(err) {
				console.log(err);
				uni.login({
					provider: that.appletsInfo.provider,
					success(res) {
						that.$u.vuex('appletsInfo.loginCode', res.code);
						// 校验code是否失效
						fun();
					}
				})
			}
		})
	} else {
		uni.login({
			provider: that.appletsInfo.provider,
			success(res) {
				that.$u.vuex('appletsInfo.loginCode', res.code);
				// 校验code是否失效
				fun();
			}
		})
	}
}

/**
 * 校验历史路由中路由出现两次以上判断
 * @param {this指向} that
 * @param {执行方法} fun
 */
export const verifyRouting = (data, key) => {
	let arrData = [...data ? data : getCurrentPages()];
	let obj = {}
	for (let i = 0; i < arrData.length; i++) {
		var item = arrData[i][key] // a为计算的属性,可换成b,c
		obj[item] = (obj[item] + 1) || 1
	}
	return obj
}

//时间格式化兼容 ios
export const formatTime2 = function(fmt, timestamp) {
	var date = new Date(timestamp) // 兼容safari
	var o = {
		'M+': date.getMonth() + 1,
		'd+': date.getDate(),
		'h+': date.getHours(),
		'm+': date.getMinutes(),
		's+': date.getSeconds(),
		'q+': Math.floor((date.getMonth() + 3) / 3),
		'S': date.getMilliseconds()
	}
	if (/(y+)/.test(fmt)) {
		fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
	}
	for (var k in o) {
		if (new RegExp('(' + k + ')').test(fmt)) {
			fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k])
				.length)))
		}
	}
	return fmt
}


// 星期格式转换 0-6：周日到周六
export const weekFormat = function(e, prefix = "周") {
	switch (e) {
		case 0:
			return prefix + "日"
			break;
		case 1:
			return prefix + "一"
			break;
		case 2:
			return prefix + "二"
			break;
		case 3:
			return prefix + "三"
			break;
		case 4:
			return prefix + "四"
			break;
		case 5:
			return prefix + "五"
			break;
		case 6:
			return prefix + "六"
			break;
		default:
			return ""
			break;
	}
}

// 转换今日的时辰格式
export const todayTimeFormat = function(e) {
	if (e >= 0 && e < 7) {
		return "凌晨"
	} else if (e >= 7 && e < 11) {
		return "上午"
	} else if (e >= 11 && e < 13) {
		return "中午"
	} else if (e >= 13 && e < 18) {
		return "下午"
	} else if (e >= 18 && e < 24) {
		return "晚上"
	} else {
		return ""
	}
}

// 是否显示周几
export const isShowWeekDay = function(sub, weekDay) {
	const currentWeekDay = new Date().getDay()
	const dayTime = 1000 * 60 * 60 * 24
	// 1.当前时间与消息时间相差必须大于2天小于7天
	// 2.当前时间距离本周一相差必须大于2天且小于当前距离周一的天数
	// 3.消息时间不可能是0-周日，因为周日没有给后面时间留空间，不会走这里的逻辑，而是走今天的逻辑
	if (sub >= dayTime && weekDay !== 0 && sub <= dayTime * currentWeekDay) {
		return true
	} else {
		return false
	}
}


// 仿微信时间显示格式转换 @time 时间戳毫秒
export const weChatTimeFormat = function(time) {
	const today = new Date().getTime()
	// 当前时间减去获取到的时间
	const sub = today - time
	const day = 1000 * 60 * 60 * 24
	const timeDate = new Date(time)
	const currentYear = new Date().getFullYear()
	const getYear = new Date(time).getFullYear()
	const HHmm = `${formatTime2("hh", timeDate)}:${formatTime2("mm", timeDate)}`
	const showWeekDay = isShowWeekDay(sub, timeDate.getDay())

	if (currentYear > getYear) {
		return `${formatTime2("yyyy年MM月dd日", timeDate)} ${todayTimeFormat(timeDate.getHours())} ${formatTime2("hh:mm", timeDate)}`
	} else if (showWeekDay) {
		return `${weekFormat(timeDate.getDay())} ${HHmm}`
	} else if (new Date(time).toDateString() === new Date().toDateString()) {
		return HHmm
	} else if (sub < day) {
		return `昨天 ${HHmm}`
	} else {
		return `${formatTime2("MM月dd日", timeDate)} ${todayTimeFormat(timeDate.getHours())} ${formatTime2("hh:mm", timeDate)}`
	}
}

/**
 * 获取图片url
 */
export function getimageUrl(name) {
	return config.imgUrl + name;
}